package com.hnguigu.health.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.plugin.Interceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

import javax.sql.DataSource;


@Configuration
@PropertySource("classpath:config.properties")
//扫描mybaties接口及映射文件
@MapperScan("com.hnguigu.health.mapper")
public class MybatiesConfig {

    @Value("${jdbc.driverClass}")
    private String driverClass;
    @Value("${jdbc.connectionURL}")
    private String url;
    @Value("${jdbc.userId}")
    private String userName;
    @Value("${jdbc.password}")
    private String passWord;

    //初始化 DataSource
    @Bean //注入spring容器
    public DataSource initDataSource(){
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClass);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(passWord);
        return dataSource;
    }

    //初始化 mybaties
    @Bean
    public MybatisSqlSessionFactoryBean initMybaties(DataSource dataSource){
        MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        //设置分页插件
        PaginationInterceptor interceptor = new PaginationInterceptor();
        sqlSessionFactoryBean.setPlugins(new Interceptor[]{interceptor});
        //设置实体类别名
        sqlSessionFactoryBean.setTypeAliasesPackage("com.hnguigu.health.pojo");
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        //标准输出日志
        configuration.setLogImpl(StdOutImpl.class);
        //开启驼峰命名
        configuration.setMapUnderscoreToCamelCase(true);
        //开启在属性为null也调用setter();
        configuration.setCallSettersOnNulls(true);
        /*sqlSessionFactoryBean.setConfiguration(configuration);*/
        return sqlSessionFactoryBean;
    }
}
